package com.thread.concurrentTest;

import org.junit.Test;

import java.util.concurrent.Semaphore;

public class SemaphoreTest {

    @Test
    public void test1() {
        // 3个停车位
        Semaphore semaphore = new Semaphore(3);

        // 6辆车
        for (int i = 0; i < 6; ++i) {
            new Thread(() -> {
                try {
                    // 抢占
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + " 抢到了车位");
                    Thread.sleep(3000);

                } catch (InterruptedException e) {
                    e.printStackTrace();

                } finally {
                    // 离开
                    semaphore.release();
                    System.out.println(Thread.currentThread().getName() + " 离开了车位");
                }
            }, String.valueOf(i)).start();
        }

        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
